# -*- coding: utf-8 -*-
from micolog_plugin import *
from model import *
import random

class RandomPostsWidget(Plugin):
	def __init__(self):
		Plugin.__init__(self,__file__)
		self.author="houkai"
		self.authoruri="http://www.houkai.com/"
		self.uri="http://www.houkai.com/"
		self.description="displays a list of random posts on your widgetized sidebar."
		self.register_filter('random_posts_widget',self.getRandomPostsWidget)
		self.register_filter('random_link',self.getRandomLink)
		self.register_urlmap('random',self.getRandomURL)
		self.name="random posts widget"
		self.version="1.2"

	def get(self,page):
		count=OptionSet.getValue("Count",default="5")
		linkText=OptionSet.getValue("LinkText",default=u"手气不错")
		return '''<h3>displays a list of random posts on your widgetized sidebar</h3>
					<form action="" method="post">
					random posts counts:<input name="Count" value="%s" /><br /><br />
					link text:<input name="LinkText" value="%s" /><br /><br />
					<input type="submit" value="submit"><br />
					</form>
					<br /><br />
					random posts widget v1.2 
					<a href="http://micolog.appspot.com/plugins/view?key=agdtaWNvbG9nch8LEgZQbHVnaW4iE3JhbmRvbSBwb3N0cyB3aWRnZXQM" 
					target="_blank">check for update</a> and 
					<a href="http://www.houkai.com/2010/06/3/micolog-random-posts-widget.html" 
					target="_blank">help</a> 
					<br /><br />
					powered by <a href="http://www.houkai.com/" target="_blank">HouKai</a>
					'''%(count,linkText)

	def post(self,page):
		count = page.param("Count")
		linkText = page.param("LinkText")
		OptionSet.setValue("Count",count)
		OptionSet.setValue("LinkText",linkText)
		return self.get(page)

	def randomPosts(self,num = 5):
		entries = Entry.all().filter('entrytype =', 'post').filter('published =', True) 
		entrycount = self.blog.entrycount #Entry.all().filter('entrytype =', 'post').filter('published =', True).count()
		if not entries or num > entrycount: 
			return entries
		rand_ids = {} 
		for i in range(0, num): 
			rand = random.randint(0, entrycount - 1) 
			while rand_ids.has_key(rand): 
				rand = random.randint(0, entrycount - 1) 
			rand_ids.update({rand:True})
		result = [] 
		for id in rand_ids.keys():
                        try:
                                result.append(entries.fetch(1, offset = id)[0])
                        except:
                                result=result
		return result

	def getRandomPostsWidget(self,page=None,*arg1,**arg2):
		widget = ''.encode('utf8')
		number = OptionSet.getValue("Count",default="5")
		randomPosts = self.randomPosts(int(number))
		for entry in randomPosts:
			widget = widget + '<li><a href="/'.encode('utf8')+entry.link.encode('utf8')+'">'.encode('utf8')+entry.title.encode('utf8')+'</a></li>'.encode('utf8')
		return widget+'<script type="text/javascript">document.getElementById("random_posts_widget").style.display="";</script>'.encode('utf8')

	def getRandomURL(self,page=None,*arg1,**arg2):
		URL = ''.encode('utf8')
		num = 1
		randomPosts = self.randomPosts(num)
		for entry in randomPosts:
			URL = '/'.encode('utf8')+entry.link.encode('utf8')
		template_values = { 'randomURL': URL }
		page.render2('views/random.html',{'randomURL': URL})
		return

	def getRandomLink(self,page=None,*arg1,**arg2):
		linkText=OptionSet.getValue("LinkText",default=u"手气不错")
		return u'<a title="随便找一篇文章给我看看吧！" rel="nofollow" href="/e/random">'.encode('utf8')+linkText.encode('utf8')+'</a>'.encode('utf8')
